using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using static UnityEngine.Rendering.DebugUI;

[Serializable]
public class EasyAnimBase
{
    public string name;
    public float multiply=1;
    public bool playOnEnable;
    public bool loop;
    public float lifeTime = 1;
    public GameObject targetObject;
    public Action endAction;
}



[Serializable]
public class ImageAnimationiui : EasyAnimBase
{
    public Gradient gradient;
}

public abstract class EasyAnimation<T> : MonoBehaviour where T : EasyAnimBase
{
    protected Coroutine animCoroutine;

    public T[] anims;

    protected virtual void Awake()
    {
        for (int i = 0; i < anims.Length; i++)
        {
            if (anims[i].targetObject == null)
            {
                anims[i].targetObject = gameObject;
            }
        }
    }

    protected virtual void OnEnable()
    {
        for (int i = 0; i < anims.Length; i++)
        {
            if (anims[i] != null && anims[i].playOnEnable)
            {
                Play(i);
            }
        }
    }


    public void Play()
    {
        Play(0);
    }

    public void Play(int id) 
    {
        if (id >= 0 && id < anims.Length)
        {
            Play(anims[id]);
        }
    }

    public void BindEndAction(int animID, Action action) 
    {
        if (animID >= 0 && animID < anims.Length)
        {
            anims[animID].endAction += action;
        }
    }


    protected void Play(T anim)
    {
        Stop();
        animCoroutine = StartCoroutine(RunAnim(anim));
    }

    public virtual void Stop()
    {
        if (animCoroutine != null)
            StopCoroutine(animCoroutine);
        animCoroutine = null;
    }

    IEnumerator RunAnim(T anim)
    {
        float t = 0;
        while (true)
        {
            ApplyAnim(anim, t / anim.lifeTime);

            t += Time.deltaTime;

            if (t > anim.lifeTime)
            {
                anim.endAction?.Invoke();

                if (anim.loop)
                {
                    t = 0;
                }
                else
                {
                    break;
                }
            }

            yield return null;
        }

        ApplyAnim(anim, 1);

        animCoroutine = null;
    }

    protected virtual void ApplyAnim(T anim, float process)
    {}
}
